﻿using System;
using System.Collections.Generic;
using System.Text;
using thinger.DataConvertLib;

namespace SerialPortDemo_07
{
    public class ByteBuffer
    {
        //固定长度的临时数组
        private byte[] TEMP_BYTE_ARRAY = new byte[1024];

        //当前数组长度
        public int CURRENT_LENGTH = 0;

        //当前指针位置
        public int CURRENT_POSITION = 0;

        //最后返回数组
        private byte[] RETURN_ARRAY;

        public ByteBuffer()
        {

        }

        public ByteBuffer(byte[] byteArray)
        {
            pushByteArray(byteArray);
        }



        public void pushByteArray(byte[] byteArray)
        {
            byteArray.CopyTo(TEMP_BYTE_ARRAY, CURRENT_LENGTH);

            CURRENT_LENGTH += byteArray.Length;
        }

        public void pushByte(byte value)
        {
            TEMP_BYTE_ARRAY[CURRENT_LENGTH++] = value;
        }

        public void pushShort(short value)
        {
            byte[] temp = ByteArrayLib.GetByteArrayFromShort(value);
            TEMP_BYTE_ARRAY[CURRENT_LENGTH++] = temp[0];
            TEMP_BYTE_ARRAY[CURRENT_LENGTH++] = temp[1];
        }

        /// <summary>
        /// 弹出一个byte类型数据，当前指针提升1位
        /// </summary>
        /// <returns></returns>
        public byte popByte()
        {
            byte value = ByteLib.GetByteFromByteArray(TEMP_BYTE_ARRAY, CURRENT_POSITION);

            CURRENT_POSITION++;

            return value;
        }

        /// <summary>
        /// 弹出一个short类型数据，当前指针提升2位
        /// </summary>
        /// <returns></returns>
        public short popShort()
        {
            if (CURRENT_POSITION + 1 >= CURRENT_LENGTH)
            {
                return 0;
            }

            short value = ShortLib.GetShortFromByteArray(TEMP_BYTE_ARRAY, CURRENT_POSITION);

            CURRENT_POSITION += 2;

            return value;
        }

        public byte[] toByteArray()
        {
            RETURN_ARRAY = new byte[CURRENT_LENGTH];

            Array.Copy(TEMP_BYTE_ARRAY, 0, RETURN_ARRAY, 0, CURRENT_LENGTH);
            return RETURN_ARRAY;
        }

    }
}
